<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>自定义网页右键菜单</title>

	<style type="text/css">
		* {
			padding: 0;
			margin: 0;
			box-sizing: border-box;
		}
		.content {
			width: 500px;
			height: 60px;
			background-color: #F5F5F5;
			border :1px solid #ccc;
			padding-top: 18px;
			color: #000;
			font-size: 20px;
			text-align: center;
			margin-top: 100px;
			margin-left: 200px;
			font-weight: bold;
			border-radius: 5px;
		}
		#right-menu {
			display: none;
			position: fixed;
			z-index: 99;
			top: 100px;
			background-color: #fff;
		}
		ul {
			width: 200px;
			border :1px solid #D9D9D9;
			border-radius: 5px;
		}
		ul li {
			list-style: none;
			font-weight: bold;
			font-size: 20px;
			padding: 10px 20px;
			cursor: pointer;
		}
	</style>
</head>
<body id="body">
	<div class="content" id="content">
		<label>right click to see the menu</label>
	</div>
	<div id="right-menu">
		<ul>
			<li class="item">menu item 1</li>
			<li class="item">menu item 2</li>
			<li class="item">menu item 3</li>
		</ul>
	</div>

<script type="text/javascript">
	var content = document.getElementById("content");
	content.addEventListener("contextmenu",rightClick,false);

	document.onclick = function() {
		var e=window.event;
		var target = e.target||e.srcElement;
		if(target.className=="item"){
			alert(target.innerText);
		}else{
			var menu = document.getElementById('right-menu');
			menu.style.display = "none";
		}
		
	}
	function rightClick(){
		var coordinate = getMousePos();
		var menu = document.getElementById('right-menu');
		menu.style.display = "block";
		menu.style.top = coordinate.y+"px";
		menu.style.left=""+coordinate.x+"px";
		var e=window.event;
		e.preventDefault();//阻止dom元素的默认行为
	}
	function getMousePos(event) {
	    var e = event || window.event;
	    var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
	    var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
	    var x = e.pageX || e.clientX + scrollX;
	    var y = e.pageY || e.clientY + scrollY;
	    return { 'x': x, 'y': y };
	}
</script>
</body>
</html>